<template>
  <div class="app-container">
    <!-- @row-save="rowSave" -->
    <!-- @row-update="rowUpdate" -->
    <avue-crud
      ref="crud"
      :option="option"
      :data="data"
      :table-loading="loading"
      @on-load="onLoad"
      @row-del="rowDel"
      :before-open="beforeOpen"
      @search-change="searchChange"
      @search-reset="resetChange"
    >
      <template
        slot="menuLeft"
        slot-scope="{}"
      >
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="rowSave"
        >
          新增
        </el-button>
      </template>
      <template
        slot="menu"
        slot-scope="{row}"
      >
        <el-button
          icon="el-icon-edit"
          @click="rowUpdate(row)"
          type="text"
        >
          编辑
        </el-button>
      </template>
      <template
        slot="icon"
        slot-scope="scope"
      >
        <div>
          <svg-icon :icon-class="scope.row.icon || '404'"></svg-icon>
        </div>
      </template>
    </avue-crud>
    <!-- 新增 编辑弹框 -->
    <el-dialog
      class="addDialog"
      :title="title"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose"
      center
    >
      <el-form
        ref="dataForm"
        :model="form"
        label-width="90px"
        :inline="true"
        :rules="formRules"
      >
        <el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="资源名称:">
                <el-input
                  v-model="form.resVal"
                  placeholder="资源名称"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上级菜单:">
                <el-select
                  v-model="form.resPid"
                  placeholder="请选择..."
                  clearable
                  ref="select"
                >
                  <!-- // 设置⼀个input框⽤作模糊搜索选项功能 -->
                  <el-input
                    class="input"
                    placeholder="此处键⼊'关键词'搜索查询"
                    prefix-icon="el-icon-search"
                    v-model="treeFilter"
                    clearable
                  >
                  </el-input>
                  <!-- // 设置⼀个隐藏的下拉选项 -->
                  <!-- // 如果不设置⼀个下拉选项，下⾯的树形组件将⽆法正常使⽤ -->
                  <el-option
                    hidden
                    key="id"
                    :value="form.resPid"
                    :label="form.selectName"
                  ></el-option>
                  <!-- // 设置树形控件 -->
                  <el-tree
                    :data="treeData"
                    :props="defaultProps"
                    :expand-on-click-node="false"
                    :check-on-click-node="true"
                    ref="tree"
                    node-key="id"
                    :default-expand-all="true"
                    :filter-node-method="filterNode"
                    @node-click="handleNodeClick"
                  >
                    <!-- // @node-click：树形控件选项点击事件 -->
                    <!-- // :expand-on-click-node：使树形控件只有点箭头图标的时候才会展开或者收缩节点，为false则点⽂字直接选中该项 -->
                    <!-- // :check-on-click-node：是否在点击节点的时候选中节点，当选项为复选框时有⽤，这个属性可以删除 -->
                    <!-- // :default-expand-all：默认展开所有节点 -->
                    <!-- // :filter-node-method：实现搜索功能的筛选⽅法 -->
                    <!-- //选项⽤插槽来显⽰，匹配搜索功能，并⽅便增加tag标签需求 -->
                    <!-- <span slot-scope="{ data }">  
                        <span>{{ data.label }}</span>
                        <el-tag
                          size="mini"
                          style="margin: 0 10px"
                          v-show="filterorgType(data.tag)"
                          >{{ filterorgType(data.tag) }}</el-tag
                        >
                      </span> -->
                  </el-tree>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="资源类型:">
                <el-select
                  v-model="form.resType"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in dicData"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="资源排序:">
                <el-input
                  type="number"
                  v-model="form.resOrder"
                  placeholder="请输入资源排序"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="是否启用:">
                <el-select
                  v-model="form.resIsvalid"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in resIsvalidDicData"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="资源路径:"
                prop="path"
              >
                <el-input
                  v-model="form.path"
                  placeholder="请输入资源路径"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="组件路径:">
                <el-input
                  v-model="form.component"
                  placeholder="请输入组件路径"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="菜单图标:">
                <el-popover
                  placement="bottom-start"
                  width="460"
                  trigger="click"
                  @show="$refs['iconSelect'].reset()"
                >
                  <IconSelect
                    ref="iconSelect"
                    @selected="selected"
                  />
                  <el-input
                    slot="reference"
                    v-model="form.iconCls"
                    placeholder="点击选择图标"
                    readonly
                  >
                    <svg-icon
                      v-if="form.iconCls"
                      slot="prefix"
                      :icon-class="form.iconCls"
                      class="el-input__icon"
                      style="height: 32px; width: 16px"
                    />
                    <i
                      v-else
                      slot="prefix"
                      class="el-icon-search el-input__icon"
                    />
                  </el-input>
                </el-popover>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item
                label="备注:"
                width="100%"
              >
                <el-input
                  type="textarea"
                  v-model="form.resDesc"
                  placeholder=""
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

        </el-row>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="dialogStatus==='create'?createData():updateData()"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addRes, getRes, upRes, delRes, getResTree } from '@/api/user.js'
import IconSelect from '@/components/IconSelect'

export default {
  components: {
    IconSelect,
  },
  data() {
    return {
      form: {
        resourceName: '', //
        selectVal: '', // select框的绑定值
        selectName: '', // 树形控件上级菜单名称
        resPid: '',
        resVal: '',
        path: '', //资源路径
        icon: '', //图标
        iconCls: '', //数据库存储图标名称
        createTime: '',
        updateTime: '',
      },
      loading: false,
      data: [],
      /* 分页 */
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
        background: false,
      },
      dialogVisible: false, //新增  编辑对话框
      title: '',
      selectVal: '', // select框的绑定值
      selectName: '', // select框显⽰的name
      treeFilter: '', // 搜索框绑定值，⽤作过滤
      // 新增编辑必填条件
      formRules: {
        path: [
          { required: true, message: 'path is required', trigger: 'blur' },
        ],
      },
      // 树形控件数据
      // treeData: [
      // {
      //   value: "1",
      //   label: "⼀级 1菈妮",
      //   tag: "wife",
      //   children: [
      //     {
      //       value: "1-1",
      //       label: "⼆级 1-1",
      //       children: [
      //         {
      //           value: "1-1-1",
      //           label: "三级 1-1-1",
      //         },
      //       ],
      //     },
      //   ],
      // },
      // {
      //   label: "⼀级 2",
      //   value: "2",
      //   children: [
      //     {
      //       value: "2-1",
      //       label: "⼆级 2-1",
      //       children: [
      //         {
      //           value: "2-1-1",
      //           label: "三级 2-1-1",
      //         },
      //       ],
      //     },
      //     {
      //       value: "2-2",
      //       label: "⼆级 2-2",
      //       children: [
      //         {
      //           value: "2-2-1",
      //           label: "三级 2-2-1鸡腿",
      //           tag: "princess",
      //         },
      //       ],
      //     },
      //   ],
      // },
      // {
      //   value: "3",
      //   label: "⼀级 3",
      //   children: [
      //     {
      //       value: "3-1",
      //       label: "⼆级 3-1",
      //       children: [
      //         {
      //           value: "3-1-1",
      //           label: "三级 3-1-1",
      //         },
      //       ],
      //     },
      //     {
      //       value: "3-2",
      //       label: "⼆级 3-2艾尔登法环",
      //       tag: "yyds",
      //       children: [
      //         {
      //           value: "3-2-1",
      //           label: "三级 3-2-1",
      //         },
      //       ],
      //     },
      //   ],
      // },
      // ],
      treeData: [
        {
          resVal: '全部',
          id: 'R',
          children: [],
        },
      ],
      defaultProps: {
        children: 'children',
        label: 'resVal',
      },
      // 标签数组
      // tagList: [
      //   { value: "wife", label: "⽼婆" },
      //   { value: "princess", label: "⼩公主" },
      //   { value: "yyds", label: "天下第⼀" },
      // ],
      // 资源类型
      dicData: [
        {
          label: '节点',
          value: 'N',
        },
        {
          label: '菜单',
          value: 'M',
        },
        {
          label: '按钮',
          value: 'B',
        },
      ],
      // 是否启用
      resIsvalidDicData: [
        {
          label: '启用',
          value: true,
        },
        {
          label: '禁用',
          value: false,
        },
      ],
      searchList: {},
      option: {
        height: 550,
        headerAlign: 'center',
        align: 'center',
        border: true,
        index: true,
        indexLabel: '序号',
        indexWidth: 100,
        card: true,
        addBtn: false,
        editBtn: false,
        defaultExpandAll: false,
        dialogDrag: false,
        menuWidth: 200,
        searchMenuSpan: 4,
        searchSpan: 6,
        searchLabelWidth: '25%',
        column: [
          {
            label: '资源名称',
            prop: 'resVal',
            align: 'left',
            search: true,
          },
          {
            label: '上级菜单',
            prop: 'resPid',
            type: 'tree',
            defaultExpandAll: true,
            expandOnClickNode: false,
            dicData: [
              {
                resVal: '全部',
                id: 'R',
                children: [],
              },
            ],
            props: {
              label: 'resVal',
              value: 'id',
            },
            rules: [
              {
                required: false,
                message: '请选择上级菜单',
                trigger: 'click',
              },
            ],
            hide: true,
          },
          /* {
            label: "资源编号",
            prop: "resCode",
            width: 150,
          }, */
          {
            label: '资源类型',
            prop: 'resType',
            type: 'select',
            dicData: [
              {
                label: '节点',
                value: 'N',
              },
              {
                label: '菜单',
                value: 'M',
              },
              {
                label: '按钮',
                value: 'B',
              },
            ],
          },
          {
            label: '资源排序',
            prop: 'resOrder',
            type: 'number',
            value: 0,
          },
          {
            label: '是否启用',
            prop: 'resIsvalid',
            type: 'select',
            value: true,
            dicData: [
              {
                label: '启用',
                value: true,
              },
              {
                label: '禁用',
                value: false,
              },
            ],
          },
          {
            label: '创建时间',
            prop: 'createTime',
            display: false,
            hide: true,
          },
          {
            label: '更新时间',
            prop: 'updateTime',
            display: false,
            hide: true,
          },
          {
            label: '资源路径',
            prop: 'path',
            rules: [
              {
                required: true,
                message: '请输入资源路径',
              },
            ],
          },
          {
            label: '组件路径',
            prop: 'component',
            rules: [
              {
                required: false,
                message: '请输入组件路径',
              },
            ],
          },
          {
            label: '菜单图标',
            prop: 'icon',
            hide: true,
            rules: [
              {
                required: false,
                message: '请输入菜单图标',
              },
            ],
          },
          {
            label: '备注',
            prop: 'resDesc',
            type: 'textarea',
            span: 24,
            overHidden: true,
          },
        ],
      },
    }
  },
  watch: {
    // 搜索过滤，监听input搜索框绑定的treeFilter
    treeFilter(val) {
      this.$refs.tree.filter(val)
      // 当搜索框键⼊值改变时，将该值作为⼊参执⾏树形控件的过滤事件filterNode
    },
  },
  methods: {
    onLoad(page, params = {}) {
      /* if (page.layout) {
        Object.assign(params, {
          page: 1,
          size: 10,
        });
      } else {
        Object.assign(params, page);
      } */
      let searchList = this.searchList
      Object.assign(params, {
        ...searchList,
        text: searchList.resVal,
        page: this.page.currentPage,
        size: this.page.pageSize,
      })
      this.loading = true
      /* if (page.text) {
                    Object.assign(params, page);
                } */
      getRes(params).then((data) => {
        this.loading = false
        this.data = data.data.records
      })
    },
    /* 清空 */
    resetChange() {
      this.page.currentPage = 1
      this.page.pageSize = 10
      this.searchList = {}
      this.onLoad()
    },
    /* 搜索筛选 */
    searchChange(params, done) {
      done()
      this.page.currentPage = 1
      this.page.pageSize = 10
      this.searchList = {
        ...params,
      }
      this.onLoad()
    },
    /* 新增 */
    // rowSave(row, done, loading) {
    //   delete row.createTime;
    //   delete row.updateTime;
    //   addRes(row).then(
    //     (data) => {
    //       if (data.status) {
    //         this.onLoad({});
    //         this.$message({
    //           type: "success",
    //           message: "操作成功!",
    //         });
    //         done();
    //       } else {
    //         this.$message.error("系统错误,请稍候再试!");
    //         loading();
    //       }
    //     },
    //     (error) => {
    //       window.console.log(error);
    //       loading();
    //     }
    //   );
    // },
    // 选择图标
    selected(name) {
      // this.form.icon = name
      this.$set(this.form, 'icon', name)
      this.form.iconCls = this.form.icon
      // this.$set(this.form, 'iconCls', name)
      // console.log(this.form.icon)
    },
    rowSave() {
      ;(this.form = {
        resourceName: '', //
        selectVal: '', // select框的绑定值
        selectName: '',
        resPid: '',
        resVal: '',
        createTime: '',
        updateTime: '',
      }),
        (this.dialogVisible = true)
      this.dialogStatus = 'create'
      this.title = '新增'
      getResTree().then((data) => {
        if (data.status) {
          this.treeData[0].children = data.data.records
        } else {
          this.$message.error('系统错误,请稍候再试!')
        }
      })
    },
    // 关闭弹框
    handleClose() {
      this.dialogVisible = false
    },
    // 新增确认事件
    createData() {
      delete this.form.createTime
      delete this.form.updateTime
      if (this.form.children) {
        delete this.form.children
      }
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          const formData = Object.assign({}, this.form)
          addRes(formData).then(
            (res) => {
              console.log(res)
              if (res.status) {
                this.dialogVisible = false
                this.onLoad({})
                this.$message({
                  type: 'success',
                  message: '操作成功!',
                })
              } else {
                window.console.log(res.message)
              }
            },
            (error) => {
              window.console.log(error)
            }
          )
        }
      })
    },
    // 编辑确认事件
    updateData() {
      delete this.form.createTime
      delete this.form.updateTime
      if (this.form.children) {
        delete this.form.children
      }
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          const formData = Object.assign({}, this.form)
          upRes(formData).then(
            (res) => {
              if (res.status) {
                this.dialogVisible = false
                this.onLoad({})
                this.$message({
                  type: 'success',
                  message: '操作成功!',
                })
              } else {
                window.console.log(res.message)
              }
            },
            (error) => {
              window.console.log(error)
            }
          )
        }
      })
    },
    // 结构树点击事件
    handleNodeClick(data) {
      // this.form.selectVal = data.value; // select绑定值为点击的选项的value
      // this.form.selectName = data.label; // input中显⽰值为label
      this.form.resPid = data.id // select绑定值为点击的选项的value
      this.form.selectName = data.resVal // input中显⽰值为label
      this.treeFilter = '' // 点击后搜索框清空
      this.$refs.select.blur() // 点击后关闭下拉框，因为点击树形控件后select不会⾃动折叠
    },
    // 模糊查询（搜索过滤），实质为筛选出树形控件中符合输⼊条件的选项，过滤掉其他选项
    filterNode(value, data) {
      if (!value) return true
      let filterRes = data.resVal.indexOf(value) !== -1
      return filterRes
    },
    // 选项卡标签（可忽略，增值迭代需求）
    filterorgType(val) {
      let arr = this.tagList.filter((item) => {
        return item.value == val
      })
      return arr.length ? arr[0].label : ''
    },
    // 修改
    rowUpdate(row) {
      this.dialogVisible = true
      this.dialogStatus = 'update'
      this.title = '编辑'
      console.log(row)
      this.form = Object.assign({}, row)
      this.form.resPid = ''
      getResTree().then((data) => {
        if (data.status) {
          this.treeData[0].children = data.data.records
          // 获取上级菜单名称
          // let index = this.treeData.findIndex((item) =>
          //   item.id == row.resPid
          // )
          for (let i = 0; i < this.treeData.length; i++) {
            if (this.treeData[i].id == row.resPid) {
              this.$set(this.form, 'selectName', this.treeData[i].resVal)
            } else {
              for (let j = 0; j < this.treeData[i].children.length; j++) {
                if (this.treeData[i].children[j].id == row.resPid) {
                  this.$set(
                    this.form,
                    'selectName',
                    this.treeData[i].children[j].resVal
                  )
                } else {
                  for (
                    let k = 0;
                    k < this.treeData[i].children[j].children.length;
                    k++
                  ) {
                    if (
                      this.treeData[i].children[j].children[k].id == row.resPid
                    ) {
                      this.$set(
                        this.form,
                        'selectName',
                        this.treeData[i].children[j].children[k].resVal
                      )
                    }
                  }
                }
              }
            }
          }
          // if (index > -1) {
          //   this.$set(this.form, 'selectName', this.treeData[index].resVal)
          // } else {
          //   let childIndex = this.treeData[0].children.findIndex((item) => item.id == row.resPid)
          //   if(childIndex > -1) {
          //     this.$set(this.form, 'selectName', this.treeData[0].children[childIndex].resVal)
          //   } else {
          //     let childIndex01 = this.treeData[0].children[15].children.findIndex((item) => item.id == row.resPid)
          //     if(childIndex01 > -1){
          //       this.$set(this.form, 'selectName', this.treeData[0].children[15].children[childIndex01].resVal)
          //     }
          //   }
          // }
          this.form.resPid = row.resPid
        } else {
          this.$message.error('系统错误,请稍候再试!')
        }
      })
    },
    /* 修改 */
    // rowUpdate(row, index, done, loading) {
    //   delete row.createTime;
    //   delete row.updateTime;
    //   upRes(row).then(
    //     () => {
    //       console.log(row)
    //       done();
    //       this.onLoad({});
    //       this.$message({
    //         type: "success",
    //         message: "操作成功!",
    //       });
    //     },
    //     (error) => {
    //       window.console.log(error);
    //       loading();
    //     }
    //   );
    // },
    /* 删除 */
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        delRes({
          id: row.id,
        }).then((res) => {
          if (res.status) {
            this.onLoad()
            this.$message({
              type: 'success',
              message: '操作成功!',
            })
          } else {
            this.$message({
              type: 'error',
              message: res.msg,
            })
          }
        })
      })
    },
    /* 打开弹窗前回调 */
    beforeOpen(done, type) {
      if (['edit', 'add'].includes(type)) {
        getResTree().then((data) => {
          if (data.status) {
            let i = this.findArray(this.option.column, 'resPid', 'prop')
            if (i > -1) {
              this.option.column[i].dicData[0].children = data.data.records
              console.log(data.data.records)
            }
          } else {
            this.$message.error('系统错误,请稍候再试!')
          }
        })
      }
      done()
    },
  },
  mounted() {},
}
</script>

<style scoped="scoped" lang="scss">
/deep/ .avue-crud__pagination {
  text-align: center;
}
/deep/ .el-card.is-always-shadow,
.el-card.is-hover-shadow:focus,
.el-card.is-hover-shadow:hover {
  box-shadow: none;
}
/deep/ .el-card {
  border: none;
}
.addDialog {
  padding: 20px 20px 20px 40px;
}
/deep/ .el-form-item {
  width: 100%;
}
/deep/ .el-form-item__content {
  width: 75%;
}
/deep/ .el-select {
  display: inline-block;
  position: relative;
  width: 100%;
}
</style>


